let listcode = ''
Page({
  data: {
    // 是否显示倒计时 
    countDownVisible: false,
    model: '',
    code: ''
  },
  onLoad({ returnUrl }) {
    this.setData({
      returnUrl
    })
  },
  validModel() {
    const reg = /^1[3-9]\d{9}$/
    const vaild = reg.test(this.data.model.trim())
    if (!vaild) wx.utils.toast('请输入正确的手机号')
    return vaild
  },
  vaildCode() {
    const reg = /^\d{6}$/
    const vaild = reg.test(this.data.code.trim())
    if (!vaild) return wx.utils.toast('请输入正确的验证码')
    return vaild
  },
  // 获取当前倒计时信息
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.seconds > 0 || ev.detail.minutes === 1
    })
  },
  // 点击获取验证码
  async getCode() {
    if (!this.validModel()) return
    const { data, code } = await wx.http.get('/code', {
      mobile: this.data.model
    })
    console.log(code)
    if (code !== 10000) return wx.utils.toast('验证码获取失败')
    console.log(data.code, '验证码')
    listcode = data.code
    // 开始倒计时
    // this.setData({
    //   countDownVisible: true
    // })
  },
  copyCode() {
    console.log(listcode)
    wx.setClipboardData({
      data: listcode
    })
  },
  async submit() {
    if (!this.validModel()) return
    if (!this.vaildCode()) return
    const { code, data } = await wx.http.post('/login', {
      mobile: this.data.model,
      code: this.data.code
    })
    console.log(code, '登录是否成功')
    if (code !== 10000) return wx.utils.toast('登录失败')
    getApp().setToken(data.token, data.refreshToken)
    wx.redirectTo({
      url: this.data.returnUrl
    })
  }
})
